package com.wksc.framework.impexp.writer;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.List;

import com.wksc.framework.impexp.log.ImpExpLog;
import com.wksc.framework.impexp.util.ClassFactory;
import jxl.read.biff.BiffException;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

/**
 * <p> Title(文件名): ${file_name} </p>
 * <p> Description(描述): ${todo} </p>
 * <p> Copyright(版权): Copyright (c) ${year} </p>
 * <p> Company(公司): 成都四方信息技术有限公司 </p>
 * <p> CreateTime(生成日期)：11-11-3下午2:58 </p>
 *
 * @author wanglei
 * @version ${project_name}
 */
public class TxtWriter extends Writer {
	//写文件的流 
	private BufferedWriter bufferedWriter;
	
	//日志记录类
	private static final ImpExpLog log = ClassFactory.getLog(TxtWriter.class);

    /**
     * 初始化TXT文件,
     * 假如createFile为true则表示需要读取文件刷新缓冲区
     * 若CreateFile为false则表示只需要获取之前的文件进行追加内容
     *
     * @throws java.io.IOException
     * @throws BiffException
     */
    @Override
	public void initWriter(File file, boolean createFile1) throws IOException,
			BiffException {
		this.file = file;
		this.createFile = createFile1;
//		if (file.exists()) { //华为问题单2447:file在之前已经创建好了,这个方案不可行
//			createFile1 = false;
//		}
		bufferedWriter = new BufferedWriter(new OutputStreamWriter(
				new FileOutputStream(file, true), "UTF-8"));
		if (createFile1) { //需要重新刷新缓冲区
			if(!file.exists() || file.length()<1){ 
				//华为问题单2447:【1月06日华为反馈问题单】DTS2013010603236 Y--SDV1--SAM--设置excel的导出最大条数是100条，选择全部导出txt文件，导出的txt文件出现了特殊符号
				bufferedWriter.write(new String(new byte[] { (byte) 0xEF,
						(byte) 0xBB, (byte) 0xBF }, "UTF-8"));
				bufferedWriter.flush();	
			}
		} else { //不刷新缓冲区,直接换新行
			bufferedWriter.newLine();
		}
	}

	@Override
	public boolean writeByRow(Object[] data, int rowNum) throws WriteException, IOException {
		if (null != data) {
			StringBuilder buf = new StringBuilder();
			for (int i = 0; i < data.length; i++) {
				buf.append(data[i]); //先获取需要写入数据的表头索引,再根据表头的索引取得数据
				buf.append("&&");
			}
			
			String lineContent = buf.toString();
			bufferedWriter.write(lineContent.substring(0, lineContent.length() - 2));
			bufferedWriter.write("\r\n");
		}
		return true;
	}

	@Override
	public boolean writeByRow(Object[] data, int rowNum, Integer[] rowIndex)
			throws WriteException {
		if (data != null) {//数据不为空循环数据
			StringBuilder buf = new StringBuilder();
			for (int i = 0; i < rowIndex.length; i++) {
				buf.append(data[rowIndex[i]]);//先获取需要写入数据的表头索引,再根据表头的索引取得数据
				buf.append("&&");
			}
			String lineContent = buf.toString();
			try {
				bufferedWriter.write(lineContent.substring(0, lineContent.length() - 2));
				bufferedWriter.write("\r\n");
			} catch (IOException e) {
				log.error("TXT write content failure!", e);
			}
		}
		return true;
	}


	@Override
	public int writeByRows(List<?> data, int startLine, Integer[] rowIndex)
			throws WriteException {
		int succNum = 0;
        for(int i = 0; i < data.size(); i++){
            if(writeByRow((Object[])data.get(i), startLine++, rowIndex)){
                 succNum++;
            }
        }
        return succNum;
	}

	@Override
	public int writeByCol(int colNum, List< String> data)
			throws WriteException, IOException {
		return 0;
	}

	@Override
	public void close() throws IOException, WriteException {
		if (null != bufferedWriter) {
			bufferedWriter.flush();
			bufferedWriter.close();
		}
	}
	
	@Override
	public int writeByRows(List<?> data, int startLine)
			throws RowsExceededException, WriteException, IOException {
		int succNum = 0;
		for(int i = 0; i < data.size(); i++){
			if(writeByRow((Object[]) data.get(i), startLine++)){
				succNum++;
			}
		}
		return succNum;
	}
}
